package com.car.advertising.permission;

import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.support.widget.JumpManager;
import com.support.widget.layout.BaseCommActivity;

import java.util.ArrayList;

import static android.R.attr.targetSdkVersion;

/**
 * Created by hdb on 2017/5/2.
 */

public class PermissionManger {
    public static final int READ_PHONE_REQUESTCODE = 1;
    PermissionListener listener;
    static PermissionManger permissionManger;
    private String[] permissions, opsPermissions;

    public static PermissionManger getInstance() {
        synchronized (PermissionManger.class) {
            if (permissionManger == null) {
                synchronized (PermissionManger.class) {
                    permissionManger = new PermissionManger();
                }
            }
        }

        return permissionManger;
    }

    public void requestPermission(BaseCommActivity activity, String[] permissions, String[] opsPermissions, int requestCode, PermissionListener listener) {
        final PackageInfo info;
        ArrayList<String> permissionList = new ArrayList<>();
        this.permissions = permissions;
        this.opsPermissions = opsPermissions;
        this.listener = listener;
        try {
            info = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
            int targetSdkVersion = info.applicationInfo.targetSdkVersion;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (targetSdkVersion >= Build.VERSION_CODES.M) {
                    for (int i = 0; i < permissions.length; i++) {
                        if (ContextCompat.checkSelfPermission(activity, permissions[i]) == PackageManager.PERMISSION_GRANTED) {
                            AppOpsManager appOpsManager = (AppOpsManager) activity.getSystemService(Context.APP_OPS_SERVICE);
                            int checkOp = appOpsManager.checkOp(opsPermissions[i], Process.myUid(), activity.getPackageName());
                            if (checkOp == AppOpsManager.MODE_IGNORED) {
                                permissionList.add(permissions[i]);
                            }
                        } else {
                            permissionList.add(permissions[i]);
                        }
                    }
                    if (permissionList.size() == 0) {
                        listener.granted();
                    } else {
                        ActivityCompat.requestPermissions(activity, permissions, requestCode);
                    }

                }
            } else {
                listener.granted();
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void onRequestPermissionsResult(final BaseCommActivity activity, @NonNull String[] permissions, int requestCode, @NonNull int[] grantResults) {
        if (requestCode == READ_PHONE_REQUESTCODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    if (targetSdkVersion >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        AppOpsManager appOpsManager = (AppOpsManager) activity.getSystemService(Context.APP_OPS_SERVICE);
                        int checkOp = appOpsManager.checkOp(opsPermissions[i], Process.myUid(), activity.getPackageName());
                        if (checkOp == AppOpsManager.MODE_IGNORED) {
                            /*妥协方案*/
                            showMessageOKCancel(activity, "请打开设置页面，获取手机信息权限", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    //// TODO: 2017/4/25 调转设置页面
                                    startSetting(activity);
                                    JumpManager.finishApplication();

                                }
                            });
                            return;
                        }
                    }
                } else {
                     /*妥协方案*/
                    showMessageOKCancel(activity, "请打开设置页面，获取手机信息权限", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            //// TODO: 2017/4/25 调转设置页面
                            startSetting(activity);
                            JumpManager.finishApplication();

                        }
                    });
                    return;
                }

            }
            listener.granted();

        }
    }

    private void showMessageOKCancel(BaseCommActivity activity, String message, DialogInterface.OnClickListener okListener) {
        Dialog d = new AlertDialog.Builder(activity)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .create();
        d.setCanceledOnTouchOutside(false);
        d.show();


    }

    /**
     * 跳转到设置界面
     */
    private void startSetting(BaseCommActivity activity) {
        if (PermissionMiuiOs.isMIUI()) {
            Intent intent = PermissionMiuiOs.getSettingIntent(activity);
            if (PermissionMiuiOs.isIntentAvailable(activity, intent)) {
                activity.startActivity(intent);
            }
        }
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            try {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                activity.startActivity(intent);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

    }
}
